package com.top10.controller;

import com.top10.bean.JwtUtil;
import com.top10.bean.ResponseBean;
import com.top10.common.WXConst;
import com.top10.common.WebConst;
import com.top10.entity.UserOpenid;
import com.top10.service.IUserOpenidService;
import com.top10.utils.MD5;
import com.top10.utils.RandomUtils;
import com.top10.utils.WXUtil;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 微信登录Controller
 * @author ellen
 * @version 1.0
 * @date 2018/10/13
 */
@RestController
@RequestMapping("/wx")
public class WxLoginController {

    @Value("${jwt.period}")
    private Long period;//token有效时间（毫秒）
    @Value(("${jwt.issuer}"))
    private String issuer;//jwt token 签发人

    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private IUserOpenidService iUserOpenidService;

    @RequestMapping("/login")
    public ResponseBean wxLogin(String code, String state, HttpServletResponse response) throws Exception {
        Map<String, String> loginMap = WXUtil.getLoginAccessToken(WXConst.APPID, WXConst.SECRET, code);
        String loginAccessToken = loginMap.get("access_token");
        String openId = loginMap.get("openid");

        if(loginAccessToken == null || loginAccessToken.equals("")){
            return ResponseBean.createError("微信授权失败");
        }

        //获取用户微信信息
        Map<String, String> userInfoMap = WXUtil.getUserInfo(loginAccessToken, openId);

        UserOpenid openid1 = new UserOpenid();
        openid1.setWxOpenid(openId);
        String uuid =RandomUtils.makeUUID();
        openid1.setUserUuid(uuid);
        iUserOpenidService.insert(openid1);

        // 制作JWT Token
        String jwtToken = jwtUtil.issueJWT(MD5.getRandomString(20),//令牌id
                uuid,//用户id
                (issuer == null ? JwtUtil.DEFAULT_ISSUER : issuer),//签发
                (period == null ? JwtUtil.DEFAULT_PERIOD : period),//token有效时间
                SignatureAlgorithm.HS512);
        //token存入 response里的Header
        response.setHeader(WebConst.TOKEN,jwtToken);

        return ResponseBean.createSuccess().setMessage("登录成功").addData("token",jwtToken).addData("userInfoMap", userInfoMap);
    }

}
